<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-08-22 17:32:49
 * @FilePath: \public-health-emergencies-fed:\radiation-hygiene-fe\src\views\slide\slideSample.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="80px"
    >
      <el-row>
        <el-col :span="5">
          <el-form-item label="登记时间" prop="formDate">
            <el-date-picker
              v-model="queryParams.formDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              clearable
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="operation">
      <el-button
        class="register"
        type="primary"
        size="mini"
        @click.native.prevent="openDialog()"
        >登记</el-button
      >
    </div>
    <el-table
      v-loading="loading"
      :data="slidesSampleList"
      :height="height - 400 + 'px'"
      @row-dblclick="(row) => openDialog(row, '3')"
    >
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="登记时间" align="center" prop="createTime" />
      <el-table-column label="数组数" align="center" prop="arraySize" />
      <el-table-column label="平均值" align="center">
        <template slot-scope="{ row }">
          {{ parseInt(row.average) }}
        </template>
      </el-table-column>
      <el-table-column label="标准差" align="center">
        <template slot-scope="{ row }">
          {{ parseInt(row.standardDeviation) }}
        </template>
      </el-table-column>
      <el-table-column label="变异系数" align="center">
        <template slot-scope="{ row }">
          {{ (row.changeRate * 100).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.status_disable"
            :value="scope.row.state"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="{ row }">
          <el-button
            v-if="row.state == '1'"
            @click.native.prevent="updateState(row, '0')"
            type="text"
          >
            启用
          </el-button>
          <el-button
            v-if="row.state == '0'"
            @click.native.prevent="updateState(row, '1')"
            type="text"
            style="color: #f32d2d"
          >
            停用
          </el-button>
          <el-button
            v-if="row.state == '1'"
            @click.native.prevent="handleDelete(row)"
            type="text"
            style="color: #f32d2d"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 登记弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      @close="closeExam"
      width="70%"
      class="sampledialog"
      v-dialogDrag="true"
    >
      <el-upload
        ref="upload"
        class="myupload"
        :action="upload.url"
        :headers="upload.headers"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleFileSuccessSecond"
        :before-upload="beforeAvatarUpload"
        :show-file-list="false"
        v-if="status != '3'"
      >
        <el-button
          class="uploadbutton"
          icon="el-icon-upload"
          size="mini"
          type="primary"
          >导入</el-button
        >
      </el-upload>

      <div class="notice">
        <div class="notice-item">
          <div class="tip color5"></div>
          5%~10%
        </div>
        <div class="notice-item">
          <div class="tip color10"></div>
          10%~15%
        </div>
        <div class="notice-item">
          <div class="tip color15"></div>
          ≥15%
        </div>
      </div>

      <div
        class="block"
        v-loading="blockloading"
        :class="status == '3' && 'view'"
      >
        <div
          class="block-item"
          :class="getColor(Number(item))"
          v-for="(item, index) in importDataList"
          :key="index"
        >
          <span>{{ item }}</span>
          <i
            v-if="status != '3'"
            class="el-icon-circle-close"
            @click="deleteData(index)"
          ></i>
        </div>
        <div class="empty" v-if="importDataList.length == 0">请导入数据</div>
      </div>

      <div class="result">
        <el-table class="mytable" v-loading="loadingResult" :data="resultList">
          <el-table-column label="数组数" align="center" prop="arraySize" />
          <el-table-column label="平均数" align="center">
            <template slot-scope="{ row }">
              {{ parseInt(row.average) }}
            </template>
          </el-table-column>
          <el-table-column label="标准差" align="center">
            <template slot-scope="{ row }">
              {{ parseInt(row.standardDeviation) }}
            </template>
          </el-table-column>
          <el-table-column label="变异系数" align="center">
            <template slot-scope="{ row }">
              {{ (row.changeRate * 100).toFixed(2) }}%
            </template>
          </el-table-column>
        </el-table>

        <div class="calc">
          <el-button type="success" v-if="status != '3'" @click="calculate()"
            >计 算</el-button
          >
          <el-button type="primary" v-if="status != '3'" @click="openName()"
            >确 认</el-button
          >
          <el-button type="primary" plain v-else @click="dialogVisible = false"
            >关 闭</el-button
          >
        </div>
      </div>
    </el-dialog>

    <!-- 名称弹框 -->
    <el-dialog
      title="确认名称"
      :visible.sync="nameVisible"
      :close-on-click-modal="false"
      v-dialogDrag="true"
    >
      <div class="nametitle">请为本次抽样填写名称</div>
      <el-form
        @submit.native.prevent
        :model="nameform"
        ref="nameform"
        :rules="rules"
        size="small"
        label-width="0px"
      >
        <el-form-item label="" prop="name">
          <el-input
            v-model="nameform.name"
            placeholder="请输入"
            clearable
            @keyup.enter.native="submitForm()"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm()">确 认</el-button>
        <el-button @click="nameVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  slidesSampleList,
  slidesSampleExport,
  slidesSampleListing,
  slidesSampleImport,
  slidesSampleDetail,
  slidesSampleCompute,
  slidesSampleAdd,
  slidesSampleEdit,
  slidesSampleDelete,
  slidesSampleUpdateState,
} from "@/api/slides/slideSample";
import { getToken } from "@/utils/auth";

export default {
  name: "slideSample",
  dicts: ["status_disable"],
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisible: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/basic/registration/slidesSample/importData",
      },
      // 视图高度
      height: document.documentElement.clientHeight,
      // 样品列表
      slidesSampleList: [],
      // 表单参数
      form: {},
      loading: false,
      status: null,
      title: null,
      // 导入后获取的数值列表
      importDataList: [],
      loadingResult: false,
      // 计算结果单条列表
      resultList: [],
      nameVisible: false,
      rules: {
        name: [
          { required: true, message: "样品名称不能为空", trigger: "change" },
        ],
      },
      nameform: {},
      fileList: [],
      // 平均值
      average: null,
      blockloading: false,
    };
  },
  created() {
    this.getList();
  },
  computed: {
    getColor() {
      return (value) => {
        if (this.average) {
          if (
            (value >= this.average * (1 + 0.05) &&
              value <= this.average * (1 + 0.1)) ||
            (value <= this.average * (1 - 0.05) &&
              value >= this.average * (1 - 0.1))
          ) {
            return "color5";
          } else if (
            (value >= this.average * (1 + 0.1) &&
              value <= this.average * (1 + 0.15)) ||
            (value <= this.average * (1 - 0.1) &&
              value >= this.average * (1 - 0.15))
          ) {
            return "color10";
          } else if (
            value >= this.average * (1 + 0.15) ||
            value <= this.average * (1 - 0.15)
          ) {
            return "color15";
          }
        }
      };
    },
  },
  methods: {
    // 获取滑片样品列表
    getList() {
      this.queryParams.createTimeStart =
        this.queryParams.formDate && this.queryParams.formDate[0];
      this.queryParams.createTimeEnd =
        this.queryParams.formDate && this.queryParams.formDate[1];
      let queryParams = { ...this.queryParams };
      delete queryParams.formDate;
      this.loading = true;
      slidesSampleList(queryParams)
        .then((response) => {
          this.slidesSampleList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 更新状态
    updateState(row, state) {
      this.$modal
        .confirm(
          `是否确认${state === "1" ? "停用" : "启用"}样品 [${row.name}] ？`
        )
        .then(() => {
          this.loading = true;
          return slidesSampleUpdateState({
            registrationSlidesSampleId: row.registrationSlidesSampleId,
            state: state,
          });
        })
        .then(() => {
          this.$modal.msgSuccess(`${state === "1" ? "停用" : "启用"}成功`);
          this.getList();
        })
        .finally(() => {});
    },
    // 打开对话框
    openDialog(row, status) {
      this.resetForm("form");
      this.importDataList = [];
      this.resultList = [];
      this.average = null;
      if (row) {
        slidesSampleDetail(row.registrationSlidesSampleId).then((response) => {
          this.importDataList = response.data.registrations;
          this.resultList = [response.data];
          this.average = response.data.average && Number(response.data.average);
          this.dialogVisible = true;
        });
        if (status == "3") {
          this.status = "3";
          this.title = "查看样品";
        } else {
        }
      } else {
        this.form = {};
        this.status = "1";
        this.title = "添加样品";
        this.dialogVisible = true;
      }
    },
    // 提交按钮
    submitForm() {
      this.$refs["nameform"].validate((valid) => {
        if (!valid) return;
        let form = {
          name: this.nameform.name,
          registrations: this.importDataList,
          ...this.resultList[0],
        };
        slidesSampleAdd(form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.dialogVisible = false;
          this.nameVisible = false;
          this.getList();
        });
      });
    },
    // 删除
    handleDelete(row) {
      this.$modal
        .confirm(`是否确认删除 [${row.name}] ？`)
        .then(() => {
          this.loading = true;
          return slidesSampleDelete(row.registrationSlidesSampleId);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 删除数据
    deleteData(index) {
      this.importDataList.splice(index, 1);
      this.calculate();
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },
    // 文件移除
    handleRemove(file, fileList) {
      console.log("handleRemove", fileList);
      this.fileList = fileList;
      this.importDataList = [];
      this.resultList = [];
      this.average = null;
    },
    // 点击文件预览
    handlePreview(file, fileList) {},
    // 移除文件
    beforeRemove(file, fileList) {
      console.log("beforeRemove", fileList);
      return this.$confirm(`确定移除 ${file.name}？`).then(() => {
        this.importDataList = [];
        this.resultList = [];
      });
    },
    // 文件上传成功处理
    handleFileSuccessSecond(response, file, fileList) {
      if (response.code == 500) {
        this.$modal.msgError(response.msg);
        return;
      }
      if (response.data && response.data.length != 0) {
        this.importDataList = response.data;
        this.resultList = [];
        this.calculate();
      }
      this.fileList = fileList;
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    // 上传前格式校验
    beforeAvatarUpload(file) {
      const isTxt = file.type === "text/plain";
      if (!isTxt) {
        this.$message.warning("仅支持txt格式，请重新上传!");
      }
      return isTxt;
    },
    // 超出数量提示
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    // 计算结果
    calculate() {
      if (this.importDataList.length == 0) {
        this.$modal.msgWarning("请导入数据");
      } else {
        this.loadingResult = true;
        this.blockloading = true;
        slidesSampleCompute(this.importDataList)
          .then((response) => {
            this.resultList = [response.data];
            this.average =
              response.data.average && Number(response.data.average);
            this.loadingResult = false;
            this.blockloading = false;
          })
          .catch((response) => {
            this.loadingResult = false;
            this.blockloading = false;
          });
      }
    },
    // 打开名称弹框
    openName() {
      if (this.importDataList.length == 0) {
        this.$modal.msgWarning("请导入数据");
      } else if (this.resultList.length == 0) {
        this.$modal.msgWarning("请计算结果");
      } else {
        this.resetForm("nameform");
        this.nameform = {};
        this.nameVisible = true;
      }
    },
    // 关闭
    closeExam() {
      if (this.status != "3") {
        this.$refs.upload.clearFiles();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.operation {
  margin-bottom: 15px;
  .register {
    padding-inline: 30px;
  }
}
.uploadbutton {
  padding-inline: 20px;
}
.el-dialog__body .el-form {
  width: fit-content;
  margin: 0 auto;
}
.myupload {
  margin-bottom: 10px;
  margin-top: -10px;
}
.result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  .calc {
    width: min-content;
    margin-left: 20px;
    .el-button {
      margin: 0;
      &:nth-of-type(1) {
        margin-bottom: 10px;
      }
    }
  }
}
.nametitle {
  text-align: center;
  margin-bottom: 10px;
  font-weight: bolder;
  &::before {
    content: "* ";
    color: red;
  }
}
::v-deep .el-table .warning-row {
  background: #d6bc149e;
}
.sampledialog ::v-deep .el-dialog {
  height: 90%;
  .el-dialog__body {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 90%;
  }
}
.block {
  flex: 1;
  overflow: auto;
  border: 1px solid #e0dfdf;
  border-radius: 5px;
  padding: 10px;
  padding-right: 0;
  &.view {
    margin-top: 30px;
  }
  &-item {
    height: 30px;
    line-height: 30px;
    text-align: center;
    padding: 0 15px 0 10px;
    display: inline-block;
    border: 1px solid #bebcbc;
    margin-right: 10px;
    margin-bottom: 10px;
    position: relative;
    color: #000;
    &:hover {
      cursor: pointer;
      .el-icon-circle-close {
        position: absolute;
        top: 0;
        right: 0;
        opacity: 1;
      }
    }
    .el-icon-circle-close {
      position: absolute;
      top: 0;
      right: 0;
      opacity: 0;
      transition: all 0.5s;
    }
  }
  .empty {
    width: 100%;
    height: 100%;
    text-align: center;
    padding-top: 245px;
    color: #999;
  }
}
.color5 {
  background: #ffdcdc;
}
.color10 {
  background: #ff6666;
}
.color15 {
  background: #d61414;
}
.notice {
  margin: 0 10px 10px auto;
  position: absolute;
  right: 0;
}
.notice-item {
  display: inline-block;
  margin-right: 10px;
}
.tip {
  display: inline-block;
  width: 20px;
  height: 10px;
}
::v-deep .el-table.mytable::before {
  display: none;
}
::v-deep .el-table.mytable .el-table__cell {
  border-bottom: none;
}
</style>
